<template>
  <el-dialog v-model="isShowDialog" title="Adjust Map" width="400px">
    <div class="params-container">
      <el-form label-width="120px">
        <el-form-item label="Chute">
          <el-input-number v-model="formData.SlotQty" :min="0" />
          <span class="unit">Unit</span>
        </el-form-item>
        <el-form-item label="Horizontal Line">
          <el-input-number v-model="formData.HorizontalBarHeight" :min="6"  :step="2" />
          <span class="unit">Unit</span>
          <el-tooltip content="6+2*N" placement="top">
            <span class="tip" style="color: red">?</span>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="Finger Spacing">
          <el-input-number v-model="formData.FingerSpacing" :min="6" :step="2"  />
          <span class="unit">Unit</span>
        </el-form-item>
        <el-form-item label="Finger">
          <el-input-number v-model="formData.FingersQty" :min="2" />
          <span class="unit">Unit</span>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">Cancel</el-button>
        <el-button type="primary" @click="confirmDialog">Ok</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { editProjectMapDetailAsync } from "/@/api/main/projectResult";
import JSZip from "jszip";
import {ElMessage, ElMessageBox} from "element-plus";

const isShowDialog = ref(false);
const imgIndex  = ref(0);

interface FormData {
  ID?: number;
  Type: number;
  SlotQty: number;
  FingersQty: number;
  HorizontalBarHeight: number;
  FingerSpacing: number;
  MinionsQty?: number;
  TotalProductionCapacity?: number;
  BicycleTotal?: number;
  ParkingSpaceQty?: number;
  DispatchAmount: number;
  ChargeStationQty?: number;
  WarehouseWidth: number;
  WarehouseLength: number;
  GoodsWidth: number;
  GoodsLength: number;
}

const formData = reactive<FormData>({
  Type: 2,
  SlotQty: 96,
  FingersQty: 2,
  HorizontalBarHeight: 10,
  DispatchAmount:2,
  FingerSpacing: 10,
  WarehouseWidth: 40,
  WarehouseLength: 40,
  GoodsWidth: 65,
  GoodsLength: 65
})

const emit = defineEmits(['update-image']);

const openDialog = (row: any,index: number) => {
  console.log('row', row);
  formData.SlotQty = row.chuteAmount;
  formData.Type = 2;
  formData.FingersQty = row.fingerCount;
  formData.ID = row.id;
  formData.MinionsQty = row.agv;
  formData.ChargeStationQty = row.chargingStations;
  formData.TotalProductionCapacity = row.totalProductCapacity;
  formData.BicycleTotal = row.singleProductCapacity;
  formData.ParkingSpaceQty = row.parkAmount;
  formData.DispatchAmount = row.dispatchAmount;
  formData.WarehouseWidth = row.warehouseWidth;
  formData.WarehouseLength = row.warehouseLength;
  formData.GoodsWidth = row.goodsWidth;
  formData.GoodsLength = row.goodsLength;

  imgIndex.value = index;
  isShowDialog.value = true;
};

const closeDialog = () => {
  isShowDialog.value = false;
  //清空输入的数据
  Object.keys(formData).forEach((key) => {
    switch (key) {
      case 'HorizontalBarHeight':
        formData.HorizontalBarHeight = 10;
        break;
      case 'FingerSpacing':
        formData.FingerSpacing = 10;
        break;
      default:
        // @ts-ignore 忽略非关键字段的 reset
        formData[key] = undefined;
    }
  });
};

const confirmDialog = async () => {
  let res;

  const gridHeight = Math.floor((formData.WarehouseLength / formData.GoodsLength) * 100);
  const gridWidth  = Math.floor((formData.WarehouseWidth / formData.GoodsWidth) * 100);

  console.log('gridHeight', gridHeight)
  console.log('gridWidth', gridWidth)


  if (formData.HorizontalBarHeight < 6 || formData.HorizontalBarHeight % 2 !== 0) {
    ElMessage.error("Horizontal Line >= 6+2N");
    return;
  }

  if (formData.FingerSpacing < 6 || formData.FingerSpacing % 2 !== 0) {
    ElMessage.error("Finger Spacing >= 6+2N");
    return;
  }

  if (formData.FingersQty < formData.DispatchAmount) {
    ElMessage.error("Finger count cannot be less than dispatch amount");
    return;
  }

  const fingerHeight = Math.ceil(Math.ceil(formData.SlotQty/2)/formData.FingersQty);
  let mapHeight = fingerHeight + formData.HorizontalBarHeight;

  let mapWidth = formData.FingersQty*4 + (formData.FingersQty - 1)*formData.FingerSpacing + 2*2

  if(mapWidth > gridWidth){
    ElMessage.error(`Current warehouse width does not support modification with finger count: ${formData.FingersQty} and finger spacing: ${formData.FingerSpacing}. Please re-enter.`);
    return;
  }

  if (mapHeight > gridHeight) {
    ElMessage.error(`Current warehouse height does not support modification with chute amount: ${formData.SlotQty} and finger count: ${formData.FingersQty} and Horizontal Bar Height
          : ${formData.HorizontalBarHeight}. Please re-enter.`);
    return;
  }


  try {
    res = await editProjectMapDetailAsync(formData);
  } catch (error) {
    await ElMessageBox.alert('Update error, please adjust parameter')
    console.error('editProjectMapDetailAsync error:', error);
    return;
  }

  // 继续处理响应数据
  const { fileContent, additionalData } = res.data.result;

  let parsedAdditionalData = {};
  try {
    parsedAdditionalData = JSON.parse(additionalData);
  } catch (e) {
    console.warn('Parse additionalData error', e);
  }

  const zip = new JSZip();
  await zip.loadAsync(fileContent, { base64: true });

  const pngFile = zip.file('t-model.png');
  const gridFile = zip.file('test.grid');

  if (pngFile) {
    const pngData = await pngFile.async('blob');
    emit('update-image', {
      pngData,
      imgIndex: imgIndex.value,
      statsData: parsedAdditionalData,
      gridFile: gridFile,
      mapId: formData.ID,
      agv: formData.MinionsQty,
      totalProductCapacity: formData.TotalProductionCapacity,
      singleProductCapacity: formData.BicycleTotal
    });
  } else {
    console.error('File t-model.png not found');
  }

  closeDialog();
};



defineExpose({
  openDialog
});
</script>

<style scoped>
.params-container {
  padding: 10px;
}

.unit {
  margin-left: 5px;
}

.tip {
  color: #909399;
  cursor: pointer;
  margin-left: 5px;
}
</style>
